/*
 * Lock.h
 *
 *  Created on: 2011-11-18
 *      Author: Owner
 */

#ifndef LOCK_H_
#define LOCK_H_

#define USE_SPIN_LOCK

#include "pthread.h"
#include "stdio.h"

#ifdef USE_SPIN_LOCK
class CLock {
public:
	CLock(){
		int ret = pthread_mutex_init(&_mutex,NULL);
		if(ret!=0){
			printf("init mutex failed: %d\n",ret);
		}
	}

	virtual ~CLock(){
		pthread_mutex_destroy(&_mutex);
	}

	void Lock(){
		int ret=0;
		if((ret = pthread_mutex_lock(&_mutex))!=0){
			printf("pthread_mutex_lock failed:%d\n",ret);
		}
	};

	void Unlock(){
		int ret=0;
		if((ret = pthread_mutex_unlock(&_mutex))!=0){
			printf("pthread_mutex_unlock failed:%d\n",ret);
		}
	};

private:
	pthread_mutex_t _mutex;
};
#else
class CLock{
private:
	pthread_spinlock_t _spinLock;

public:
	CLock(){
		if(0 != pthread_spin_init(&_spinLock,0)){
			printf("failed to init spin lock.\n");
		}
	}

	virtual ~CLock(){
		if(0 != pthread_spin_destroy(&_spinLock)){
			printf("failed to destroy spin lock.\n");
		}
	}

	void Lock(){
		if(0 != pthread_spin_lock(&_spinLock)){
			printf("failed to lock spinlock.\n");
		}
	}

	void Unlock(){
		if( 0 != pthread_spin_unlock(&_spinLock)){
			printf("failed to unlock spinlock.\n");
		}
	}
};
#endif

class CSpinLock{
private:
	pthread_spinlock_t _spinLock;

public:
	CSpinLock(){
		if(0 != pthread_spin_init(&_spinLock,0)){
			printf("failed to init spin lock.\n");
		}
	}

	virtual ~CSpinLock(){
		if(0 != pthread_spin_destroy(&_spinLock)){
			printf("failed to destroy spin lock.\n");
		}
	}

	void Lock(){
		if(0 != pthread_spin_lock(&_spinLock)){
			printf("failed to lock spinlock.\n");
		}
	}

	void Unlock(){
		if( 0 != pthread_spin_unlock(&_spinLock)){
			printf("failed to unlock spinlock.\n");
		}
	}
};

#endif /* LOCK_H_ */
